package model;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;

import view.IView;

public class Image implements IModel {
	
	private ArrayList<IView> views;
	private BufferedImage image;
	private String imagePath;
	private boolean enable;
	private boolean new_image;
	
	public Image() {
		views = new ArrayList<IView>();
		enable = true;
		new_image = false;
	}
	
	@Override
	public void registerObserver(IView view) {
		views.add(view);
	}
	
	@Override
	public void removeObserver(IView view) {
		views.remove(view);
	}
	
	@Override
	public void notifyObservers() {
		for(IView i : views) {
			i.update();
		}
	}
	
	public BufferedImage getImage() {
		return image;
	}
	
	public java.awt.Image getScaledImage(double zoom) {
		if(enable)
			return image.getScaledInstance(((int)(getWidth() * zoom)), ((int)(getHeight() * zoom)), 0);
		else
			return image.getScaledInstance(1, 1, 0);
	}
	
	private void setImage(BufferedImage image) {
		this.image = image;
		notifyObservers();
	}
	
	public void setImagePath(String imagePath) throws IOException {
		this.imagePath = imagePath;
		setImage(ImageIO.read(new File(imagePath)));
		enable();
		new_image = true;
	}
	
	public void disable() {
		enable = false;
	}
	
	public void enable() {
		enable = true;
	}
	
	public boolean isEnable() {
		return enable;
	}
	
	public boolean isNew() {
		if(new_image) {
			new_image = false;
			return true;
		}
		else
			return false;
	}
	
	public int getWidth() {
		if(enable)
			return image.getWidth();
		else
			return 1;
	}
	
	public String getPath() {
		return imagePath;
	}
	
	public int getHeight() {
		if(enable)
			return image.getHeight();
		else
			return 1;
	}
	
}